package com.ccx.coachsite.downloadmgr;

import java.lang.ref.WeakReference;
import java.util.HashMap;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;


/**
 * 模式:为每个异步加载的图片开启一个线程
 * @author cfb
 *
 */
public class AsyncImageLoaderDetail {

	 private HashMap<String, WeakReference<Drawable>> imageCache;
	  
	     public AsyncImageLoaderDetail() {
	    	 imageCache = new HashMap<String, WeakReference<Drawable>>();
	     }
	  
	     public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) {
	    	 
	         if (imageCache.containsKey(imageUrl)) {
	             WeakReference<Drawable> softReference = imageCache.get(imageUrl);
	             Drawable drawable = softReference.get();
	             if (drawable != null) {
	                 return drawable;
	             }
	         }
	         final Handler handler = new Handler() {
	             public void handleMessage(Message message) {
	                 imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
	             }
	         };
	         
	         Thread t = new Thread() {
	             @Override
	             public void run() {
	                 Drawable drawable = ImageCacheTool.loadImageFromUrl(ImageCacheTool.getRealDownUrl(imageUrl));
	                 imageCache.put(imageUrl, new WeakReference<Drawable>(drawable));
	                 Message message = handler.obtainMessage(0, drawable);
	                 handler.sendMessage(message);
	             }
	         };
	         t.start();
	         
	         return null;
	     }

	  
	    public interface ImageCallback {
	       public void imageLoaded(Drawable imageDrawable, String imageUrl);
	    }	
	    
	    public void releaseImageCache(){
	    	if (imageCache==null) return;
	    	int i=1;
	    	for (WeakReference<Drawable> weakReference : imageCache.values()) {
	             Drawable drawable = weakReference.get();
	             if (drawable != null) {
	            	 drawable.setCallback( null );
	             }
	    	}
	    	
	    	imageCache.clear();	    	 
	    }

}
